﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TargetRotate : MonoBehaviour {

    public Transform Target;

    public float distance = 5.0f;

    public float speed = 5.0f;

    public float min = -360f;
    public float max = 360f;

    private float x = 0.0f;
    private float y = 0.0f;

    private void Start()
    {
        SyncAngles();
        Zoom();
    }

    public void SyncAngles()
    {
        Vector3 angles = transform.eulerAngles;
        x = angles.y;
        y = angles.x;
    }

    private void LateUpdate()
    {
        if (Input.GetMouseButton(0))
        {
            float deltaX = Input.GetAxis("Mouse X");
            float deltaY = Input.GetAxis("Mouse Y");
            deltaX = deltaX * speed;
            deltaY = deltaY * speed;
            x += deltaX;
            y -= deltaY;
            y = ClampAngle(y, min, max);
            Zoom();
        }
    }

    private void OnEnable()
    {
        y = transform.localEulerAngles.x;
        x = transform.localEulerAngles.y;
    }

    public void Zoom()
    {
        Quaternion rotation = Quaternion.Euler(y, x, 0);
        transform.rotation = rotation;

        Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
        Vector3 position = rotation * negDistance + Target.position;
        transform.position = position;
    }


    public static float ClampAngle(float angle, float min, float max)
    {
        if (angle < -360F)
        {
            angle += 360F;
        }
        if (angle > 360F)
        {
            angle -= 360F;
        }
        return Mathf.Clamp(angle, min, max);
    }

}
